<template>
  <div class="workflow-create">
    <div class="header">
      <h2>创建工作流</h2>
      <div class="actions">
        <el-button @click="$router.back()">返回</el-button>
        <el-button 
          type="primary" 
          @click="saveAndNext" 
          :loading="saving"
        >
          下一步
        </el-button>
        <el-button 
          @click="saveWorkflow" 
          :loading="saving"
        >
          保存
        </el-button>
      </div>
    </div>

    <el-steps :active="currentStep" finish-status="success" class="steps">
      <el-step title="基本信息" />
      <el-step title="参数配置" />
      <el-step title="完成" />
    </el-steps>

    <el-form 
      ref="formRef"
      :model="workflowForm"
      :rules="rules"
      label-width="120px"
      class="workflow-form"
    >
      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <span>基本信息</span>
          </div>
        </template>

        <el-form-item label="名称" prop="name">
          <el-input v-model="workflowForm.name" placeholder="请输入工作流名称" />
        </el-form-item>

        <el-form-item label="功能描述" prop="description">
          <el-input
            v-model="workflowForm.description"
            type="textarea"
            :rows="3"
            placeholder="请描述此工作流的主要功能和使用场景"
          />
        </el-form-item>

        <el-form-item label="作者" prop="author">
          <el-input 
            v-model="workflowForm.author" 
            placeholder="请输入作者名称"
          />
        </el-form-item>

        <el-form-item label="模型类型" prop="model_type">
          <el-select 
            v-model="workflowForm.model_type" 
            placeholder="请选择模型类型"
          >
            <el-option label="Stable Diffusion" value="sd" />
            <el-option label="Midjourney" value="mj" />
            <el-option label="DALL-E" value="dalle" />
            <el-option label="其他" value="other" />
          </el-select>
        </el-form-item>

        <el-form-item label="分类" prop="category">
          <el-select 
            v-model="workflowForm.category" 
            placeholder="请选择分类"
            @change="handleCategoryChange"
          >
            <el-option label="文生图" value="text2img" />
            <el-option label="图生图" value="img2img" />
            <el-option label="人物肖像" value="portrait" />
          </el-select>
        </el-form-item>

        <el-form-item label="预览图" prop="preview_image">
          <el-upload
            class="preview-uploader"
            :show-file-list="false"
            :before-upload="beforePreviewUpload"
            :http-request="uploadPreview"
          >
            <img
              v-if="workflowForm.preview_image"
              :src="workflowForm.preview_image"
              class="preview-image"
            />
            <el-icon v-else class="preview-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-card>


      <el-card class="form-card">
        <template #header>
          <div class="card-header">
            <span>ComfyUI 工作流配置</span>
            <el-button 
              type="primary" 
              size="small"
              @click="importWorkflowClick"
            >
              导入工作流
            </el-button>
          </div>
        </template>

        <el-form-item label="工作流 JSON">
          <el-input
            v-model="workflowJsonStr"
            type="textarea"
            :rows="15"
            :disabled="true"
            placeholder="请导入 ComfyUI 工作流 JSON"
          />
        </el-form-item>

        <!-- 添加隐藏的文件输入框 -->
        <input
          type="file"
          ref="fileInput"
          style="display: none"
          accept=".json"
          @change="handleFileImport"
        />
      </el-card>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { request } from '@/utils/request'


interface WorkflowForm {
  name: string;
  description: string;
  author: string;
  model_type: string;
  category: string;
  preview_image: string;
  template_id: string;
  param_schema: Record<string, any>;
  workflow_json: Record<string, any>;
}

const router = useRouter()
const route = useRoute()
const formRef = ref()
const saving = ref(false)
const currentStep = ref(1)
const templates = ref<Template[]>([])
const showTemplateSelect = ref(false)
const fileInput = ref<HTMLInputElement | null>(null)
const workflowJsonStr = computed(() => {
  return JSON.stringify(workflowForm.value.workflow_json, null, 2)
})

const workflowForm = ref<WorkflowForm>({
  name: '',
  description: '',
  author: '',
  model_type: '',
  category: '',
  preview_image: '',
  template_id: '',
  param_schema: {},
  workflow_json: {}
})

const rules = {
  name: [
    { required: true, message: '请输入工作流名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入功能描述', trigger: 'blur' }
  ],
  author: [
    { required: true, message: '请输入作者名称', trigger: 'blur' }
  ],
  model_type: [
    { required: true, message: '请选择模型类型', trigger: 'change' }
  ],
  category: [
    { required: true, message: '请选择分类', trigger: 'change' }
  ]
}

// 处理分类变更
const handleCategoryChange = async (category: string) => {
  if (category) {
    showTemplateSelect.value = true
    try {
      const response = await request(`/api/templates?category=${category}`)
      templates.value = response.data || []
    } catch (error) {
      console.error('获取模板列表失败:', error)
      ElMessage.error('获取模板列表失败')
    }
  } else {
    showTemplateSelect.value = false
    templates.value = []
  }
}

// 处理模板选择
const handleTemplateChange = async (templateId: string) => {
  if (templateId) {
    try {
      const template = templates.value.find(t => t.id === templateId)
      if (template) {
        workflowForm.value.param_schema = template.param_schema || {}
        workflowForm.value.workflow_json = template.workflow_json || {}
      }
    } catch (error) {
      console.error('获取模板详情失败:', error)
      ElMessage.error('获取模板详情失败')
    }
  }
}

// 上传预览图前的验证
const beforePreviewUpload = (file: File) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!')
    return false
  }
  return true
}

// 自定义上传预览图
const uploadPreview = async (options: any) => {
  try {
    const formData = new FormData()
    formData.append('file', options.file)
    
    const response = await request('/api/v1/upload', {
      method: 'POST',
      body: formData,
      headers: {
        // 移除 Content-Type，让浏览器自动设置 multipart/form-data
        'Content-Type': undefined
      }
    })
    
    if (response.url) {
      workflowForm.value.preview_image = response.url
      options.onSuccess()
      ElMessage.success('图片上传成功')
    } else {
      throw new Error('上传失败')
    }
  } catch (error) {
    console.error('上传失败:', error)
    ElMessage.error('图片上传失败')
    options.onError()
  }
}

// 保存并进入下一步
const saveAndNext = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
  } catch (error) {
    return
  }

  saving.value = true
  try {
    const response = await request('/api/workflows', {
      method: 'POST',
      body: JSON.stringify(workflowForm.value)
    })
    
    ElMessage.success('保存成功')
    
    // 根据分类跳转到对应的通用模板
    const templateRoutes = {
      'text2img': '/templates/text2img',
      'img2img': '/templates/img2img',
      'portrait': '/templates/portrait'
    }
    
    const nextRoute = templateRoutes[workflowForm.value.category]
    if (nextRoute) {
      router.push({
        path: nextRoute,
        query: { 
          workflow_id: response.id,
          mode: 'create'
        }
      })
    } else {
      ElMessage.warning('未找到对应的模板页面')
    }
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

// 保存工作流
const saveWorkflow = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
  } catch (error) {
    return
  }

  saving.value = true
  try {
    await request('/api/workflows', {
      method: 'POST',
      body: JSON.stringify(workflowForm.value)
    })
    
    ElMessage.success('保存成功')
    router.push('/workflows')
  } catch (error) {
    console.error('保存失败:', error)
  } finally {
    saving.value = false
  }
}

// 获取工作流详情
const fetchWorkflowDetail = async (id: string) => {
  try {
    const response = await request(`/api/workflows/${id}`)
    workflowForm.value = {
      ...workflowForm.value,
      ...response,
      param_schema: response.param_schema || {},
      workflow_json: response.workflow_json || {}
    }
    console.log(response)
    // // 如果有分类，加载对应的模板列表
    // if (response.category) {
    //   await handleCategoryChange(response.category)
    // }
    
    // // 如果有模板ID，设置选中的模板
    // if (response.template_id) {
    //   workflowForm.value.template_id = response.template_id
    // }
  } catch (error) {
    console.error('获取工作流详情失败:', error)
    ElMessage.error('获取工作流详情失败')
  }
}

// 点击导入按钮
const importWorkflowClick = () => {
  fileInput.value?.click()
}

// 处理文件导入
const handleFileImport = async (event: Event) => {
  const input = event.target as HTMLInputElement
  const file = input.files?.[0]
  
  if (!file) return
  
  try {
    const text = await file.text()
    const json = JSON.parse(text)
    
    // 验证是否是有效的 ComfyUI 工作流
    if (!json.nodes || !Array.isArray(json.nodes)) {
      throw new Error('无效的 ComfyUI 工作流文件')
    }
    
    workflowForm.value.workflow_json = json
    ElMessage.success('工作流导入成功')
  } catch (error) {
    console.error('工作流导入失败:', error)
    ElMessage.error('工作流导入失败，请确保文件格式正确')
  } finally {
    // 清理文件输入，允许重复选择同一文件
    input.value = ''
  }
}

// 在 onMounted 中添加数据加载
onMounted(async () => {
  const workflowId = route.query.workflow_id as string
  if (workflowId) {
    await fetchWorkflowDetail(workflowId)
  }
})
</script>

<style scoped>
.workflow-create {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.steps {
  margin-bottom: 30px;
}

.workflow-form {
  max-width: 1200px;
}

.form-card {
  margin-bottom: 20px;
}

.card-header {
  font-weight: bold;
}

.preview-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 200px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-uploader:hover {
  border-color: #409EFF;
}

.preview-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 40px;
  height: 40px;
}

.actions {
  display: flex;
  gap: 12px;
}

.template-option {
  display: flex;
  align-items: center;
  padding: 8px;
}

.template-preview {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  margin-right: 12px;
}

.template-info {
  flex: 1;
}

.template-name {
  font-weight: bold;
  margin-bottom: 4px;
}

.template-desc {
  font-size: 12px;
  color: #666;
}
</style> 